import 'dart:convert';

import 'package:boss/http/api/api_helper.dart';

import 'package:boss/main.dart';
import 'package:boss/models/commodity.dart';
import 'package:boss/models/sku.dart';
import 'package:boss/textStyle/text_style.dart';

import 'package:boss/ui/page/member/utils/method.dart';
import 'package:boss/ui/widget/alert/alert.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/form/new_base_text_form_field.dart';
import 'package:boss/ui/widget/form/select_form_field.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:boss/ui/widget/picker/commodityPicker/commodity_picker.dart';
import 'package:boss/ui/widget/form/title_switch.dart';

import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:router/annotation.dart';

@RouterConfig(gradeAddandEdit.pageName)
class gradeAddandEdit extends StatefulWidget {
  static const pageName = '/gradeAddandEditPage';

  @Autowired()
  bool type;

  @Autowired()
  dynamic item;

  gradeAddandEdit({
    this.type,
    this.item,
  });

  MygradeAddandEdit createState() => MygradeAddandEdit(type == true ? '新增等级' : '编辑等级');
}

class MygradeAddandEdit extends BaseState<gradeAddandEdit> {
  dynamic itemData;

  List<Commodity> noParticipationNum = [];

  List<Commodity> noNeedCollect = [];

  bool _type;

  String screen = '1';

  String discount = '0';

  String rankName = '';

  //金额达到
  num targetAmount = 0;

  //金额原始值
  String targetAmountString;

  //是否默认等级
  int isDefaultRank = 0; //0否1是
  //赠送积分
  int giveScore = 0;

  //折扣
  num discountRate = 0;

  //折扣原始值
  String discountRateString;

  MygradeAddandEdit(String pageName) : super(pageName);

  @override
  void initState() {
    super.initState();

    _type = widget.type;

    if (widget.item != null) {
      itemData = widget.item;
      rankName = widget.item["rankName"];
      screen = widget.item["upgradeConditionType"].toString();
      discount = widget.item["discountCategory"].toString();
      targetAmount = (widget.item["targetAmount"] == null ? 0 : (widget.item["targetAmount"]) / 100);
      isDefaultRank = widget.item["isDefaultRank"];
      giveScore = widget.item["giveScore"];
      discountRate = (widget.item["extra"] == null ? 0 : num.parse(discountNumbrFormat((json.decode(widget.item["extra"])["discountRate"]) / 10)));
      noNeedCollect = [];
      if (widget.item["extra"] != null) {
        var addCommodityDiscountFormListArr = json.decode(widget.item["extra"])["addCommodityDiscountFormList"];
//        print(addCommodityDiscountFormListArr);

        for (var z in addCommodityDiscountFormListArr) {
          var newCommodity = new Commodity();
          newCommodity.id = z["commodityId"];
          if (z["skuId"] != null) {
            var sku = Sku();
            sku.skuId = z["skuId"];
            newCommodity.sku = sku;
          } else {
            newCommodity.sku = null;
          }

          noNeedCollect.add(newCommodity);
        }
      }

      if (noNeedCollect.length != 0) {
        queryWholeMenu();
      }
    }

//    setState(() {});
  }

  //查询全部菜品
  queryWholeMenu() async {
    try {
//      showLoadingToast();
      var res = await queryMenuCategory();
      if (!res.successful()) {
        toast(res.msg);
        return;
      }
      noParticipationNum = [];
      (res.data ?? []).forEach((element) {
        (noNeedCollect ?? []).forEach((str) {
          var resArr = (element.commodityList ?? []).where((item) => item.id == str.id).toList();
          if (resArr.length != 0) {
            resArr.forEach((e) {
              noParticipationNum.add(Commodity.fromJson(e.toJson()));
            });
          }
        });
      });
      List<Commodity> newNoCollectArr = noNeedCollect.where((element) => element?.sku?.skuId != 0).toList();
      noParticipationNum.forEach((element) {
        if (element.commoditySkuList.length != 0) {
          for (var i = 0; i < newNoCollectArr.length; i++) {
            var res = element.commoditySkuList.indexWhere((str) => str.commodityId == newNoCollectArr[i].id && str.skuId == newNoCollectArr[i].sku.skuId);
            if (res != -1) {
              element.sku = Sku.fromJson((element.commoditySkuList[res]).toJson());
              newNoCollectArr.removeAt(i);
              break;
            }
          }
        }
      });

      setState(() {});
    } catch (e) {} finally {
//      hideLoadingToast();
    }
  }

  //新增会员等级
  addMemberGrade() async {
    if (rankName == '') {
      toast("等级名称不能为空");
      return null;
    }

    if (screen != "1") {
      if (targetAmount == null || targetAmount == 0) {
        toast("金额达到数值不能为0或空");
        return null;
      }

      if (targetAmountString.toString().split(".").length > 2) {
        toast("金额达到数值规格有误");
        return null;
      }
      if (targetAmountString.toString().split(".").length == 2) {
        if (targetAmountString.toString().split(".")[1].length > 2) {
          toast("金额达到数值最大保留两位小数");
          return null;
        }
      }
    }

    if (discount == "1") {
      if (discountRateString == '.') {
        toast("打折数值格式有误");
        return null;
      }

      if (discountRateString != null) {
        if (discountRateString.split(".").length > 2) {
          toast("打折数值格式有误");
          return null;
        }
      }

      if (discountRate == null) {
        toast("折扣数值不能为空");
        return null;
      }

      if (discountRate > 10 || discountRate == 10) {
        toast("折扣数值不能大于等于10");
        return null;
      }

      if (num.parse(discountRate.toString()) == 0) {
        toast("折扣数值不能为0");
        return null;
      }
    }

    if (giveScore == null) {
      toast("赠送积分不能为空");
      return null;
    }

    List<Map> newArr = [];
    for (var x in noParticipationNum) {
      newArr.add({
        "commodityId": x.id,
        "skuId": x.sku == null ? 0 : (x.sku.skuId ?? 0),
      });
    }

    Map extraObject = {
      "discountRate": discount == "1" ? discountRate * 10 : 0,
      "addCommodityDiscountFormList": newArr,
    };

    try {
      showLoadingToast();

      if (_type == true) {
        var res = await api.addMemberRank({
          'upgradeCondition': int.parse(screen),
          //1无升级规则2充值3消费4充值或消费
          'discountCategory': int.parse(discount),
          'targetAmount': (screen == "1" ? 0 : (targetAmount * 100)),
          'rankName': rankName,
          'isDefaultRank': isDefaultRank,
          'giveScore': giveScore,
          'extra': extraObject,
        });

        if (res.successful()) {
          toast("新增成功");

          Future.delayed(Duration(milliseconds: 300), () async {
            Navigator.pop(context, true);
          });
        } else {
          toast(res.msg);
        }
      } else {
//     print("_____");
//     print(screen is String);
//     print(screen);

        var res = await api.updateMemberRank({
          'id': (widget.item["id"]),
          "addMemberRankForm": {
            'upgradeCondition': int.parse(screen),
            //1无升级规则2充值3消费4充值或消费
            'discountCategory': int.parse(discount),
            'targetAmount': (screen == '1' ? 0 : ((targetAmount) * 100)),
            'rankName': rankName,
            'isDefaultRank': isDefaultRank,
            'giveScore': giveScore,
            'extra': extraObject,
          }
        });

        if (res.successful()) {
          toast("更改成功");

          Future.delayed(Duration(milliseconds: 300), () async {
            Navigator.pop(context, true);
          });
        } else {
          toast(res.msg);
        }
      }
    } catch (e) {} finally {
      hideLoadingToast();
    }
  }

  //删除对应的会员等级
  deleteMember(id) async {
    var res = await api.deleteMemberRank(id);

    if (res.successful()) {
      toast("删除成功");
      Navigator.pop(context, true);
      Future.delayed(Duration(milliseconds: 100), () async {
        Navigator.pop(context, true);
      });
    } else {
      toast(res.msg);
    }
  }

  contentList() {
    return Expanded(
      child: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.only(
            left: 28.w,
            right: 28.w,
          ),
          child: Column(
            children: <Widget>[
              BaseTextFormField(
                prefixText: '等级名称',
                isRequired: false,
                hintText: '请输入',
                initialValue: rankName.toString() ?? '',
                onChanged: (value) {
                  rankName = value;
                  setState(() {});
                },
              ),
              Container(
                child: SelectFormField<String>(
                  title: '自动升级条件',
                  hintText: '请选择',
                  items: [
                    {"name": "无升级规则", "key": 1},
                    {"name": "充值", "key": 2},
                    {"name": "消费", "key": 3},
                    {"name": "充值或消费", "key": 4},
                  ].map((item) => SelectItem(value: item["key"].toString(), title: item["name"])).toList(),
                  value: screen,
                  onChanged: (value) {
                    screen = value;
                    setState(() {});
                  },
                ),
              ),
              screen != '1'
                  ? Row(
                      children: <Widget>[
                        Expanded(
                          child: BaseMoneyTextFormField(
                            moneyPattern: true,
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(RegUtil.numberReg),
                            ],
                            maxLength: 8,
                            prefixText: '金额达到',
                            isRequired: true,
                            hintText: '请输入',
                            initialValue: targetAmount == null ? '' : targetAmount.toString(),
                            onChanged: (value) {
                              targetAmountString = value;
                              if (value == '') {
                                targetAmount = null;
                                return null;
                              }

                              targetAmount = num.parse(value);
                              setState(() {});
                            },
                          ),
                        ),
                        Text(
                          "元",
                          style: TextStyleConstant().normal_1_28,
                        ),
                      ],
                    )
                  : Container(),
              Container(
                child: SelectFormField<String>(
                  title: '可享优惠',
                  hintText: '请选择',
                  items: [
                    {"name": "无优惠", "key": 0},
                    {"name": "整单折扣", "key": 1},
                    {"name": "菜品会员价", "key": 2},
                  ].map((item) => SelectItem(value: item["key"].toString(), title: item["name"])).toList(),
                  value: discount,
                  onChanged: (value) {
                    discount = value;
                    setState(() {});
                  },
                ),
              ),
              discount == "1"
                  ? Row(
                      children: <Widget>[
                        Expanded(
                          child: BaseTextFormField(
                            inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                            prefixText: '折扣',
                            isRequired: false,
                            maxLength: 3,
                            hintText: '打折数值不能超过10',
                            initialValue: discountRate == null ? '' : discountRate.toString(),
                            onChanged: (value) {
                              discountRateString = value;
                              print(value);
                              if (value == '') {
                                discountRate = null;
                                return null;
                              }
                              if (discountRateString == '.') {
                                toast("打折数值格式有误");
                                return null;
                              }
                              if (discountRateString.split(".").length > 2) {
                                toast("打折数值格式有误");
                                return null;
                              }
                              discountRate = num.parse(value);
                              setState(() {});
                            },
                          ),
                        ),
                        Text(
                          "折",
                          style: TextStyleConstant().normal_1_28,
                        ),
                      ],
                    )
                  : Container(),
              if (discount == "1")
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      height: 80.w,
                      color: Colors.white,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          RichText(
                            text: TextSpan(text: '不参与活动菜品', style: TextStyleConstant().normal_1_28, children: [
                              TextSpan(
                                text: '（${noParticipationNum.length}）',
                                style: TextStyleConstant().origin_24,
                              ),
                            ]),
                          ),
                          LabelButton(
                            title: '       +选择菜品',
                            textStyle: TextStyleConstant().blue_28,
                            onTap: () async {
                              var res = await showCommodityPicker(
                                context,
                                selectedCommodities: noParticipationNum,
                                isShowSku: true,
                              );
                              if (res != null) {
                                setState(() {
                                  noParticipationNum = res;
                                });
                              }
                            },
                          ),
                        ],
                      ),
                    ),
                    if (noParticipationNum.length != 0)
//                      Text("${((noParticipationNum ?? []).map((e) => (e.title ?? '')+(e.sku!=null?'(${e.sku.skuName ?? '--'})':'')).toList()).join(',')}",
//                          style:TextStyleConstant().normal_2_28,
//                      ),
                      Wrap(
                        direction: Axis.horizontal,
                        children: (noParticipationNum ?? [])
                            .map((e) => Stack(
                                  children: [
                                    Container(
                                      margin: EdgeInsets.symmetric(
                                        horizontal: ScreenUtil.instance.setWidth(8),
                                        vertical: ScreenUtil.instance.setWidth(10),
                                      ),
                                      padding: EdgeInsets.symmetric(
                                        horizontal: ScreenUtil.instance.setWidth(16),
                                        vertical: ScreenUtil.instance.setWidth(8),
                                      ),
                                      decoration: BoxDecoration(
                                        color: Color.fromRGBO(87, 112, 246, .16),
                                        borderRadius: BorderRadius.circular(
                                          24.w,
                                        ),
                                      ),
                                      child: Text(
                                        "${(e.title ?? '') + (e.sku != null ? '(${e.sku.skuName ?? '--'})' : '')}",
                                        style: TextStyleConstant().blue_24,
                                      ),
                                    ),
                                    Positioned(
                                      right: ScreenUtil.instance.setWidth(0),
                                      top: ScreenUtil.instance.setHeight(0),
                                      child: GestureDetector(
                                        onTap: () {
                                          noParticipationNum.remove(e);
                                          setState(() {});
                                        },
                                        child: Icon(
                                          Icons.cancel,
                                          size: 34.sp,
                                          color: Color.fromRGBO(204, 204, 204, 1),
                                        ),
                                      ),
                                    )
                                  ],
                                ))
                            .toList(),
                      ),
                  ],
                ),
              Row(
                children: <Widget>[
                  Expanded(
                    child: BaseTextFormField(
                      inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.integerReg)],
                      maxLength: 8,
                      prefixText: '赠送积分',
                      isRequired: false,
                      hintText: '请输入',
                      initialValue: giveScore == null ? '' : giveScore.toString(),
                      onChanged: (value) {
                        if (value == '') {
                          giveScore = null;
                        }
                        giveScore = num.parse(value);
                        setState(() {});
                      },
                    ),
                  ),
                  Text(
                    "分",
                    style: TextStyleConstant().normal_1_28,
                  ),
                ],
              ),
              TitleSwitch(
                title: '新会员默认此等级',
                value: (isDefaultRank == 0 ? false : true),
                onChanged: (value) {
                  if (isDefaultRank == 0) {
                    isDefaultRank = 1;
                  } else {
                    isDefaultRank = 0;
                  }
                  setState(() {});
                },
              ),
              Container(
                padding: EdgeInsets.only(
                  top: 24.w,
                  bottom: 50.w,
                ),
                width: double.infinity,
                child: Text(
                  "", //* 该等级有20个会员
                  textAlign: TextAlign.start,
                  style: TextStyleConstant().normal_3_22,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(
        title: _type == true ? '新增等级' : '编辑等级',
        actions: <Widget>[
          _type == true
              ? Container()
              : LabelButton(
                  title: '删除',
                  onTap: () {
                    showAlert(
                      context,
                      content: '确认是否删除该等级，已存在该等级下的会员不会变动可继续享受对应会员特权并可继续升级为其他会员，如不可享受请手动修改对应会员的会员等级。',
                      onCancel: (context) {
                        Navigator.pop(context);
                      },
                      onConfirm: (context) {
                        if (widget.item["isInitialRank"] == 1) {
                          toast("初始化会员等级不能删除");
                        } else {
                          deleteMember(widget.item["id"]);
                        }
                      },
                    );
                  },
                ),
        ],
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            contentList(),
            FixedBottomBtn(
              title: "保 存",
              onTap: () {
                if (_type == true) {
                  //新增
                  addMemberGrade();
                } else {
                  //编辑保存
                  addMemberGrade();
                }
              },
              isShowShadow: false,
            ),
          ],
        ),
      ),
    );
  }
}
